// 新闻首页
<template>
  <div class="index">
    <!-- 顶部栏制作 -->
    <div class="header">
      <!-- 左侧logo -->
      <div class="logo">
        <span class="iconfont iconnew"></span>
      </div>
      <!-- 中间搜索 -->
      <div class="search" @click="$router.push({path:'/search'})">
        <!-- 使用vant库插入图标 -->
        <van-icon class="search_icon" name="search" />
        <span class="cont">搜索热点</span>
      </div>
      <!-- 用户登录入口 -->
      <div class="user">
        <van-icon name="manager-o" @click="jump" />
      </div>
    </div>
    <!-- 添加标签页,添加粘性布局/滑动切换 -->
    <van-tabs v-model="active" swipeable sticky>
      <van-tab :title="value.name" v-for="value in cateList" :key="value.id">
        <!-- 内容模块 -->
        <van-pull-refresh v-model="value.loading" @refresh="onRefresh">
          <van-list
            v-model="value.loading"
            :finished="value.finished"
            finished-text="我是有底线的"
            loading-text="正玩命加载中"
            @load="loadMore"
            :immediate-check="false"
            :offset="10"
          >
            <artblock v-for="v in value.postList" :key="v.id" :post="v"></artblock>
            <!-- 把新成员传给子组件 -->
          </van-list>
        </van-pull-refresh>
      </van-tab>
    </van-tabs>
    <span class="iconfont more"></span>
  </div>
</template>

<script>
// 引入请求方法
import { getCateList } from "@/apis/cate";
import { getPostList } from "@/apis/articles";
// 使用封装内容组件
import artblock from "../components/artblock";

export default {
  components: {
    artblock,
  },
  data() {
    return {
      // active对应的是索引；无论用户是否登录，都要默认选择 头条 栏目
      active: localStorage.getItem("news") ? 1 : 0,
      cateList: [], //栏目列表数据
    };
  },
  // 1.侦听器中的方法名称必须与想侦听的属性名一样
  // 2.一般没有返回值，不能调用；但是可以。。
  watch: {
    async active() {
      // console.log("当前的栏目id是：", this.cateList[this.active].id);
      let id = this.cateList[this.active].id;
      // 页面没有加载过，才重新加载
      if (this.cateList[this.active].postList.length == 0) {
        // 根据取到的数据渲染页面
        this.init();
      }
    },
  },
  methods: {
    // 跳转到个人中心页
    jump() {
      let userinfo = JSON.parse(localStorage.getItem("news2")) || {};
      let userid = userinfo.id;
      console.log(userid);
      this.$router.push({ path: "/personal/" + userid });
    },
    // 下拉刷新
    onRefresh() {
      // 回到第一页
      this.cateList[this.active].pageIndex = 1;
      // 清空当前栏目数据
      this.cateList[this.active].postList.length = 0;
      //重新请求包含新数据
      setTimeout(async () => {
        let posts = await getPostList({
          category: this.cateList[this.active].id,
          pageIndex: this.cateList[this.active].pageIndex,
          pageSize: this.cateList[this.active].pageSize,
        });
        // 将获取的数据追加在栏目数组
        this.cateList[this.active].postList.push(...posts.data.data);
        // 加载状态结束
        this.cateList[this.active].loading = false;
        this.cateList[this.active].finished = false;
      }, 2000);
    },
    // 加载更多数据
    loadMore() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      setTimeout(async () => {
        // 加载当前页的下一页数据
        this.cateList[this.active].pageIndex++;
        // 请求数据
        let posts = await getPostList({
          category: this.cateList[this.active].id,
          pageIndex: this.cateList[this.active].pageIndex,
          pageSize: this.cateList[this.active].pageSize,
        });
        console.log(posts);
        // 将获取到的数据存储追加当前栏目的postlist数组中
        this.cateList[this.active].postList.push(...posts.data.data);
        // 加载状态结束
        this.cateList[this.active].loading = false;

        // 数据全部加载完成
        if (this.cateList[this.active].pageSize > posts.data.data.length) {
          this.cateList[this.active].finished = true;
        }
      }, 2000);
    },

    async init() {
      let id = this.cateList[this.active].id;
      // 获取指定栏目的文章数据
      let posts = await getPostList({
        category: id, //id
        pageIndex: 1, //页码
        pageSize: 5,
      });
      console.log(posts);
      // 将获取的数据存储到当前栏目的postlist数组中
      this.cateList[this.active].postList = posts.data.data;
      console.log(this.cateList);
    },
  },
  // 一进入页面
  async mounted() {
    // 分析:入口是在.van-sticky元素上加了伪元素，其依赖的是元素本身，点击本身就是点击了入口

    // 跳转到频道管理页面（入口）
    document.querySelector(".van-sticky").onclick = (e) => {
      if (e.target.className == "van-sticky") {
        console.log(this);
        //跳转到频道管理页面
        this.$router.push({
          path: "/cateManage",
        });
      }
    };
    this.cateList =
      JSON.parse(localStorage.getItem("my_toutiao_cateSave_52")) || [];
    if (this.cateList.length == 0) {
      // 获取栏目数据
      let res = await getCateList();
      console.log(res);
      this.cateList = res.data.data;
    } else {
      if (localStorage.getItem("news")) {
        this.cateList.unshift(
          {
            id: 0,
            name: "关注",
            is_top: 1,
          },
          { id: 999, name: "头条", is_top: 1 }
        );
      } else {
        this.cateList.unshift({ id: 999, name: "头条", is_top: 1 });
      }
    }

    // 改造数据,为数据添加新成员
    //每个栏目都有属于自己的文章数据/分页操作数据/下拉刷新的标识/上拉加载更多的标识
    this.cateList = this.cateList.map((value) => {
      return {
        ...value,
        postList: [], //添加栏目数组进来
        pageIndex: 1,
        pageSize: 6,
        loading: false,
        finished: false,
      };
    });
    console.log(this.cateList);
    this.init();
  },
};
</script>

<style lang="less" scoped>
.index {
  .header {
    height: 40 * 100vw/360;
    display: flex;
    justify-content: space-between;
    background-color: #f00;
    align-items: center;
    color: #fff;
    .search {
      position: relative;
      flex: 1;
      height: 30 * 100vw/360;
      background-color: rgba(255, 255, 255, 0.4);
      border-radius: 15 * 100vw/360;
      text-indent: 15 * 100vw/360;
      .search_icon {
        font-size: 20 * 100vw/360;
        margin-top: 5 * 100vw/360;
      }
      .cont {
        position: absolute;
        left: 70 * 100vw/360;
        font-size: 14 * 100vw/360;
        line-height: 30 * 100vw/360;
      }
    }
    .van-icon {
      font-size: 24 * 100vw/360;
      padding: 0 10 * 100vw/360;
    }
    .iconfont {
      font-size: 50 * 100vw/360;
      padding: 0 10 * 100vw/360;
    }
  }

  // 渲染vant组件内部，需要在前面加/deep/
  /deep/.van-sticky {
    padding-right: 50 * 100vw/360;
    &::after {
      content: "+";
      position: absolute;
      top: 0;
      right: 0;
      width: 51 * 100vw/360;
      height: 42 * 100vw/360;
      background: #fff;
      text-align: center;
      line-height: 44 * 100vw/360;
      font-size: 30 * 100vw/360;
    }
  }
}
</style>